import { Component, OnInit } from '@angular/core';
import { MessagerService } from '@farris/ui-messager';
import { NotifyService } from '@farris/ui-notify';
import { DgControl } from '@farris/designer-ui';
import { DomService, FormBasicService, FormViewModel } from '@farris/designer-services';

@Component({
    selector: 'app-form-settings',
    templateUrl: './form-settings.component.html',
    styleUrls: ['./form-settings.component.css']
})
export class FormSettingsComponent implements OnInit {
    options;

    // 支持静态文本属性的控件
    inputControlWithTextArea = [
        DgControl.TextBox.type, DgControl.MultiTextBox.type,
        DgControl.NumericBox.type, DgControl.DateBox.type,
        DgControl.LookupEdit.type, DgControl.EnumField.type,
        DgControl.TimePicker.type, DgControl.LanguageTextBox.type,
        DgControl.InputGroup.type, DgControl.Avatar.type,
        DgControl.NumberRange.type, DgControl.TimeSpinner.type,
        DgControl.RichTextBox.type,
        DgControl.PersonnelSelector.type, DgControl.OrganizationSelector.type
    ];

    /** 表单渲染方式 */
    public renderModes = [{ value: 'compile', name: '编译' }, { value: 'dynamic', name: '动态渲染' }];

    public rootViewModel: FormViewModel;

    /** 变更集提交策略 */
    public changeSetPolicyList = [{ value: 'valid', name: '仅合法变更' }, { value: 'entire', name: '全部变更' }];

    /** 是否为组件类模板 */
    public isComponentTemplate = false;

    constructor(
        private domServ: DomService,
        private notifyServ: NotifyService,
        private msgServ: MessagerService,
        public formBasicServ: FormBasicService) { }

    ngOnInit() {
        this.options = this.domServ.options;
        this.rootViewModel = this.domServ.module.viewmodels.find(v => !v.parent);

        this.isComponentTemplate = ['list-component', 'tree-component', 'list-view-component'].includes(this.domServ.module.templateId);
    }

    /**
     * 刷新静态文本
     */
    refreshInputTextArea() {

        const status = this.options.enableTextArea ? '启用' : '关闭';
        this.msgServ.question('输入类控件将' + status + '静态文本属性，确定刷新？', () => {
            this.domServ.components.forEach(cmp => {
                if (cmp.componentType && cmp.componentType.startsWith('form')) {
                    this.changeInputTextArea(cmp);
                }
            });
            this.notifyServ.success('刷新成功');
        });
    }

    /**
     * 修改卡片组件内输入控件的静态文本属性
     */
    private changeInputTextArea(domJson: any) {

        if (this.inputControlWithTextArea.includes(domJson.type)) {
            domJson.isTextArea = this.options.enableTextArea;
            return;
        }
        if (domJson.contents) {
            for (const content of domJson.contents) {
                this.changeInputTextArea(content);
            }
        }
    }

}
